<?php

namespace Frieza\Modules\Position\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel;
use Doraemon\cache\PositionModule\BaseInfo;
use Doraemon\cache\PositionModule\Rules;
use Doraemon\cache\PositionModule\UserProfile as cUserProfile;
use Doraemon\cache\UserNoter;
use Doraemon\model\Position\PositionAdType;
use Doraemon\model\Position\PositionBaseInfo;
use Doraemon\model\Position\PositionCustomRules;
use Doraemon\model\Position\PositionRules;
use Doraemon\service\position\AdmOperationModule;
use Doraemon\service\position\PositionApi;
use Doraemon\service\position\UserProfileModule;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;

class UserProfileController extends Controller
{



    /**
     * 快速修改
    */
    public function adTypeModify($id, Request $request)
    {
        try {
            $name = $request->input('name');
            $value = $request->input('value');
            if ($id && $name) {
                PositionAdType::update([$name => $value], ['id' => $id]);
            }
            return response()->json([
                'status' => true,
                'message' => '修改成功',
            ]);
        } catch (\Exception $e) {
            return response()->json(['errors' => [$message = $e->getMessage()]], 422);
        }
    }

    /**
     * 删除
     */
    public function adTypeDel($id)
    {
        $status = true;
        $message = "删除成功";
        try {

            if ($id) PositionAdType::update(['type_status' => PositionAdType::STATUS_DELETE], ['id' => $id]);

        } catch (\Exception $e) {
            $status = false;
            $message = "操作失败,信息:" . $e->getMessage();
        }

        return response()->json(compact('status', 'message'));
    }

    /**
     * 排序
     */
    public function adTypeSort(Request $request)
    {
        $sortInfo = $request->input('sort');
        $ids = array_keys($sortInfo);
        if (empty($ids)) return;
        foreach ($ids as $k => $id) {
            $sort = 127 - $k;
            PositionAdType::update(['sort' => $sort], ['id' => $id]);
        }
    }

    /**
     * 列表
     */
    public function adType(Request $request, Content $content)
    {
        // 保存数据
        if ($type_name = $request->post('type_name')) {
            $position_config = $request->post('position_config');
            $bg_color = $request->post('bg_color');
            PositionAdType::insert(compact('type_name', 'position_config', 'bg_color'));
            admin_toastr('新增记录成功', 'success');
        }
        $list = PositionAdType::select('*', ['type_status' => PositionAdType::STATUS_NORMAL, 'ORDER' => ['sort' => 'DESC']]);
        $gridModel = new GridDataModel($list);
        $grid = Admin::grid($gridModel, function (Grid $grid) use ($gridModel) {
                $grid->disableExport();
                $grid->disableFilter();
                $grid->disableCreateButton();
                $grid->disableRowSelector();
                $grid->disablePagination();
                $grid->column('id', '占位资源位id')->sort();
                $grid->column('bg_color', '背景颜色')->editable();
                $grid->column('type_name', '资源位名称')->editable();
                $grid->column('position_config', '资源位配置')->editable();
                $grid->actions(function (Grid\Displayers\Actions $actions) {
                    $actions->disableEdit();
                });
            });

        $tab = new Tab();
        $tab->add('列表信息', $grid->render());

        $form = new Form();
        $form->text('type_name', '资源位名称');
        $form->text('position_config', '资源位配置');
        $form->color('bg_color', '背景颜色');

        $header = '占位资源位列表';
        return $content
            ->header($header)
            ->description(' ')
            ->breadcrumb(['text' => $header])
            ->row($form)
            ->row($tab);
    }

//    public function userProfile(Request $request, Content $content)
//    {
//        $uid = $request->input('uid', 0);
//        $gridModel = new GridDataModel($list = $uid > 0 ? CheckUserProfile::positionTimes($uid) : []);
//        $functionModel = new GridDataModel($list = $uid > 0 ? CheckUserProfile::functionTimes($uid) : []);
//        $detailGrid = self::userProfileGrid($gridModel, $uid);
//        $functionGrid = self::userFunctionGrid($functionModel, $uid);
//        Admin::script($this->userProfileScript());
//        $tab = new Tab();
//        $html = $uid > 0 ? [
//            CheckUserProfile::display(CheckUserProfile::getCacheUserProfile($uid), '缓存数据'),
//            CheckUserProfile::display(CheckUserProfile::getEsUserProfile($uid), 'es数据'),
//        ] : [];
//        $userProfileHtml = "<div class='alert row'>" . implode('', $html) . "</div>";
//        $userProfileHtml .= "<div class='alert row'>" . CheckUserProfile::display(CheckUserProfile::getDbUserProfile($uid), 'mariadb数据', 12). "</div>";
//
//        $tab->add('资源位请求次数列表', $userProfileHtml . $detailGrid->render() . $functionGrid->render());
//
//        $header = '用户分群信息';
//        return $content
//            ->header($header)
//            ->description(' ')
//            ->breadcrumb(['text' => '资源位配置管理', 'url' => route('position.admin')], ['text' => $header])
//            ->row($tab);
//    }

    public static function userProfileGrid($gridModel, $uid = 0)
    {
        return Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel, $uid) {
                $grid->tools(function ($tools) use ($uid) {
                    if ($uid > 0) {
                        $tools->append('<div class="btn-group download" style="margin-right: 10px">
    <a class="btn btn-sm btn-twitter reload-es" data-uid="' . $uid . '" title="清除个人分群缓存"><i class="fa fa-remove"></i><span class="hidden-xs"> 清除个人分群缓存</span></a>
</div>');
                    }
                });
                $grid->disableExport();
                //筛选
                $grid->filter(function ($filter) use ($uid) {
                    // 去掉默认的id过滤器
                    $filter->disableIdFilter();
                    $filter->equal('uid', '用户uid');
                    //条件展开
                    $filter->expand();
                });
                $grid->disableCreateButton();
                $grid->disableRowSelector();
                $grid->disablePagination();
                $grid->column('name', '资源位名称');
                $grid->column('info_id', '资源位配置id');
                $grid->column('day_times', '每天第N次加载');
                $grid->column('start_times', '单次启动App过程中第N次加载');
                $grid->actions(function (Grid\Displayers\Actions $actions) use ($uid) {
                    $actions->disableEdit();
                    $actions->disableDelete();
                    $actions->disableView();
                    if ($actions->row->info_id > 0) {
                        $actions->prepend('<a class="fa fa-remove reload-data" data-uid="' . $uid . '" data-info_id="' . $actions->row->info_id . '" data-position_id="' . $actions->row->position_id . '" href="javascript:void(0);")>清除缓存</a>');
                    }
                });
            });
    }

    public static function userFunctionGrid($gridModel, $uid = 0)
    {
        return Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel, $uid) {
                $grid->disableExport();
                $grid->disableFilter();
                $grid->disableCreateButton();
                $grid->disableRowSelector();
                $grid->disablePagination();
                $grid->column('name', '使用功能名称');
                $grid->column('date', '最后一次使用日期');
                $grid->actions(function (Grid\Displayers\Actions $actions) use ($uid) {
                    $actions->disableEdit();
                    $actions->disableDelete();
                    $actions->disableView();
                    if ($actions->row->time) {
                        $actions->prepend('<a class="fa fa-remove reload-function" data-uid="' . $uid . '" data-function_id="' . $actions->row->function_id . '" href="javascript:void(0);")>清除缓存</a>');
                    }
                });
            });
    }

    private function userProfileScript()
    {
        $noterUrl = route('position.delNoter');
        $url = route('position.delCache');
        return <<<EOF
$('.reload-es').on('click', function() {
    var _this = $(this);
    var uid = $(this).data('uid');
    swal({
        title: "确认删除该用户的分群缓存信息吗？",
        type: "warning",
        showCancelButton: true,
        confirmButtonColor: "#DD6B55",
        confirmButtonText: "确认",
        showLoaderOnConfirm: true,
        cancelButtonText: "取消",
        preConfirm: function() {
            $.post('{$url}', {type:1, uid:uid}, function(result) {
                if(result.code == 1) {
                    toastr.success(result.msg, null, {
                        timeOut : 1000
                    });   
                                        $.admin.reload();
        
                } else {
                    toastr.error(result.msg, null, {
                        timeOut : 1000
                    }); 
                                        $.admin.reload();
                }   
            });
        }
    });
    
});
$('.reload-function').on('click', function() {
    var _this = $(this);
    var function_id = $(this).data('function_id');
    var uid = $(this).data('uid');
    swal({
        title: "确认删除该用户的缓存信息吗？",
        type: "warning",
        showCancelButton: true,
        confirmButtonColor: "#DD6B55",
        confirmButtonText: "确认",
        showLoaderOnConfirm: true,
        cancelButtonText: "取消",
        preConfirm: function() {
            $.post('{$noterUrl}', {function_id:function_id, uid:uid}, function(result) {
                if(result.code == 1) {
                    toastr.success(result.msg, null, {
                        timeOut : 1000
                    });   
                                        $.admin.reload();
        
                } else {
                    toastr.error(result.msg, null, {
                        timeOut : 1000
                    }); 
                                        $.admin.reload();
                }   
            });
        }
    });
    
});
$('.reload-data').on('click', function() {
    var _this = $(this);
    var info_id = $(this).data('info_id');
    var position_id = $(this).data('position_id');
    var uid = $(this).data('uid');
    swal({
        title: "确认删除该用户的缓存信息吗？",
        type: "warning",
        showCancelButton: true,
        confirmButtonColor: "#DD6B55",
        confirmButtonText: "确认",
        showLoaderOnConfirm: true,
        cancelButtonText: "取消",
        preConfirm: function() {
            $.post('{$url}', {position_id:position_id, info_id:info_id, uid:uid}, function(result) {
                if(result.code == 1) {
                    toastr.success(result.msg, null, {
                        timeOut : 1000
                    });   
                                        $.admin.reload();

                } else {
                    toastr.error(result.msg, null, {
                        timeOut : 1000
                    }); 
                                        $.admin.reload();
                }   
            });
        }
    });
});
EOF;

    }

    public function delCache(Request $request)
    {
        $code = 1;
        try {
            $params = $request->all();
            $position_id = $params['position_id'] ?? 0;
            $info_id = $params['info_id'] ?? 0;
            $uid = $params['uid'] ?? 0;
            $type = $params['type'] ?? 0;

            switch ($type) {
                case 0:
                    if (!$position_id || !$info_id) {
                        throw new \Exception('参数有误');
                    }
//                    $rdsStartKey = ApiCounter::getKey($uid, $position_id);
//                    $rdsDayKey = ApiCounter::getKey($uid, $position_id, 'day');
//                    ApiCounter::hDel($rdsStartKey, $info_id);
//                    ApiCounter::hDel($rdsDayKey, $info_id);
                    break;
                case 1:
                    if (!$uid) {
                        throw new \Exception('参数有误');
                    }
                    cUserProfile::delItem($uid);
                    break;
            }

            $msg = '删除成功';

        } catch (\Exception $e) {
            $code = 0;
            $msg = $e->getMessage();
        }
        return compact('code', 'msg');
    }

    public function delNoter(Request $request)
    {
        $code = 1;
        try {
            $params = $request->all();
            $function_id = $params['function_id'] ?? '';
            $uid = $params['uid'] ?? 0;

            if (!$function_id || !$uid) {
                throw new \Exception('参数有误');
            }
            UserNoter::callUsed($uid, $function_id, 'd');
            $msg = '删除成功';
        } catch (\Exception $e) {
            $code = 0;
            $msg = $e->getMessage();
        }
        return compact('code', 'msg');
    }

    public function delPosition(Request $request)
    {
        $code = 1;
        try {
            $params = $request->all();
            $position_id = $params['position_id'] ?? '';

            if (!$position_id) {
                throw new \Exception('参数有误');
            }
            $nowDate = date('Y-m-d H:i:s');

            $ids = PositionBaseInfo::select('id', [
                'OR' => [
                    'end_show_time[>]' => $nowDate,
                    'show_type' => PositionBaseInfo::SHOW_TYPE_ALWAYS
                ],
                'position_id' => $position_id,
                'info_status' => PositionBaseInfo::STATUS_NORMAL,
            ]);
            BaseInfo::admDelItem($position_id, $ids);
            $msg = '删除成功';
        } catch (\Exception $e) {
            $code = 0;
            $msg = $e->getMessage();
        }
        return compact('code', 'msg');
    }

    public function customSave(Request $request, $id = 0)
    {
        $id = $request->input('id', 0);
        $custom_name = $request->input('custom_name', '');
        $userProfile = $request->input('user_profile', []);

        try {

            $rs = UserProfileModule::rules($userProfile);
            $rules = $rs['rules'] ?? [];

            if ($custom_name === '') throw new \Exception('自定义分群名称不能为空');
            if (empty($rules)) throw new \Exception('分群信息不能为空');

            $id = PositionCustomRules::addCustomRule($id, Admin::user()->id, $custom_name);

            //添加分群信息
            AdmOperationModule::addUserProfile($id, $rs, PositionRules::MODULE_TYPE_CUSTOM, true);

            $success = new MessageBag([
                'title' => ($id > 0 ? '编辑' : '添加') . '成功'
            ]);

            //重新设置缓存
            Rules::delItem($id, Rules::getPrefixKey(PositionRules::MODULE_TYPE_CUSTOM));

            return redirect(route('position.customList'))->with(compact('success'));

        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => '操作失败,信息:' . $e->getMessage()
            ]);
            return back()->withInput()->with(compact('error'));
        }
    }

    public function customCreate(Request $request, Content $content, $id = 0)
    {
        $info = $id ? PositionCustomRules::getCustomInfo($id, function (&$v) {
            $v['user_profile'] = AdmOperationModule::getPositionRulesById($v['id'], PositionRules::MODULE_TYPE_CUSTOM, true);
        }) : [];
        $form = new Form($info);
        $form->action(route('position.customSave'));
        $form->disableReset();
        $form->hidden('id');
        $form->text('custom_name', '自定义分群名称')->required();
        $form->userProfile('user_profile', '用户分群')->options()->generate(false);
        $tab = new Tab();
        $tab->add('基础信息', $form);
        $header = ($id > 0 ? '编辑' : '添加') . '自定义分群';
        return $content->header($header)->description(' ')->breadcrumb(
            ['text' => '自定义分群列表', 'url' => route('position.customList')],
            ['text' => $header])->row($tab);
    }

    public function customDel($id)
    {
        $status = true;
        $message = "删除成功";
        try {
            $info = $id ? PositionCustomRules::getCustomInfo($id) : [];

            if (empty($info)) throw new \Exception('删除信息不存在');
            if (!Admin::user()->isAdministrator() && ($info['admin_id'] == Admin::user()->id)) throw new \Exception('权限不足');

            PositionCustomRules::delCustom($id);

        } catch (\Exception $e) {
            $status = false;
            $message = "操作失败,信息:" . $e->getMessage();
        }

        return response()->json(compact('status', 'message'));
    }

    public function customSort(Request $request)
    {
        $sortInfo = $request->input('sort');

        if (empty($sortInfo)) return;

        foreach ($sortInfo as $id => $sort) {
            PositionCustomRules::sort($id, $sort);
        }
    }

    public function custom(Request $request, Content $content)
    {

        $response = PositionCustomRules::getCustomList(Admin::user()->id, function (&$v, $k, $ids) {
            $rulesMap = PositionApi::activeRules($ids, PositionRules::MODULE_TYPE_CUSTOM);
            $v['user_profile'] = $rulesMap[$v['id']] ?? [];
            if ($v['edittime'] == '0000-00-00 00:00:00') $v['edittime'] = '-';
        });
        $gridModel = new GridDataModel($response);
        $grid = Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel) {
                $grid->tools(function ($tools) {

                });
                $grid->disableFilter();
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->column('id')->sort();
                $grid->column('custom_name', '自定义分群名称');
                $grid->column('user_profile', '分群信息')->userProfile();
                $grid->column('addtime', '添加时间');
                $grid->column('edittime', '最近一次修改时间');
                $grid->actions(function (Grid\Displayers\Actions $actions) {
                    $actions->disableView();
                });
            });

        $tab = new Tab();
        $tab->add('列表信息', $grid->render());

        $header = '自定义分群列表';
        return $content
            ->header($header)
            ->description(' ')
            ->breadcrumb(['text' => $header])
            ->row($tab);
    }

}
